package com.qingluan.dd;


import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.qingluan.Database.MissionDataBase;
import com.qingluan.Database.Personal_Info_database;
import com.qingluan.arguments.ARGUMENTS;
import com.qingluan.dd.InetTool.UpdateMission;
import com.qingluan.dd.InetTool.UpdateMission.AfterSuccessListener;
import com.qingluan.dd.util.SystemUiHider;
import com.qingluan.geo.BaiduLocationServer;
import com.qingluan.geo.MapMainActivity;
import com.qingluan.widget.BitmapHelper;
import com.qingluan.widget.AddTagTimeActivity;
import com.qingluan.widget.DetailInfoFactoryActivity;
import com.qingluan.widget.TimeHelper;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class MissionSignFullscreenActivity extends Activity {
	/**
	 * Whether or not the system UI should be auto-hidden after
	 * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
	 */
	private static final boolean AUTO_HIDE = true;

	/**
	 * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
	 * user interaction before hiding the system UI.
	 */
	private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

	/**
	 * If set, will toggle the system UI visibility upon interaction. Otherwise,
	 * will show the system UI visibility upon interaction.
	 */
	private static final boolean TOGGLE_ON_CLICK = true;

	/**
	 * The flags to pass to {@link SystemUiHider#getInstance}.
	 */
	private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;

	/**
	 * The instance of the {@link SystemUiHider} for this activity.
	 */
	private SystemUiHider mSystemUiHider;
	private ImageView my_picture;
	private ImageView mission_create_picture;
	private TextView mission_create_name;
	private TextView mission_create_describe;
	private TextView continue_time;
	private TextView access_num;
	private Button mission_place;
	
	private ProgressDialog progress ;
	//intent arguments 
	private static final int DetailInfoFactory_TAG = ARGUMENTS.DetailInfoFactory_TAG;
	private static final int AddTag_TAG = ARGUMENTS.AddTag;
	private static final int TakePhoto_TAG = ARGUMENTS.TakephotoCode;
	private static final int Choose_place = ARGUMENTS.Choose_place;
	//context arguments
	private Context context_this_activity;
	private String uid;
	//web arguments
	private String UpdateUrl = ARGUMENTS.CREATE_IP;
	private String ImageUrl = ARGUMENTS.PICTURE_IP;
	//map argu area
	private BaiduLocationServer LocationServer ;
	private int[] User_geo_info  ;
	private String User_addrStr = null;
	//my mission argument
	private ArrayList<String>Tag_list = new ArrayList<String>();
	private int[] GEO_INFO ;
	private String AddrStr  = null;
	private int turn = 0;
	private boolean ifCreateSuccess = false;
	//log argu area
	private static String tag = MissionSignFullscreenActivity.class.getName();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_mission_sign_fullscreen);

		uid = getIntent().getExtras().getString("uid");
		
		final View controlsView = findViewById(R.id.fullscreen_content_controls);
		final View contentView = findViewById(R.id.my_content_peroson);
		
		context_this_activity = getApplicationContext();
		// Set up an instance of SystemUiHider to control the system UI for
		// this activity.
		mSystemUiHider = SystemUiHider.getInstance(this, contentView,
				HIDER_FLAGS);
		mSystemUiHider.setup();
		mSystemUiHider
				.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
					// Cached values.
					int mControlsHeight;
					int mShortAnimTime;

					@Override
					@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
					public void onVisibilityChange(boolean visible) {
						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
							// If the ViewPropertyAnimator API is available
							// (Honeycomb MR2 and later), use it to animate the
							// in-layout UI controls at the bottom of the
							// screen.
							if (mControlsHeight == 0) {
								mControlsHeight = controlsView.getHeight();
							}
							if (mShortAnimTime == 0) {
								mShortAnimTime = getResources().getInteger(
										android.R.integer.config_shortAnimTime);
							}
							controlsView
									.animate()
									.translationY(visible ? 0 : mControlsHeight)
									.setDuration(mShortAnimTime);
						} else {
							// If the ViewPropertyAnimator APIs aren't
							// available, simply show or hide the in-layout UI
							// controls.
							controlsView.setVisibility(visible ? View.VISIBLE
									: View.GONE);
						}

						if (visible && AUTO_HIDE) {
							// Schedule a hide().
							delayedHide(AUTO_HIDE_DELAY_MILLIS);
						}
					}
				});

		// Set up the user interaction to manually show or hide the system UI.
		contentView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (TOGGLE_ON_CLICK) {
					mSystemUiHider.toggle();
				} else {
					mSystemUiHider.show();
				}
			}
		});

		// Upon interacting with UI controls, delay any scheduled hide()
		// operations to prevent the jarring behavior of controls going away
		// while interacting with the UI.
		findViewById(R.id.post_mission).setOnTouchListener(
				mDelayHideTouchListener);
		
		/**
		 * initialization ...
		 */
		Initialization();
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		// Trigger the initial hide() shortly after the activity has been
		// created, to briefly hint to the user that UI controls
		// are available.
		delayedHide(100);
	}

	/**
	 * Touch listener to use for in-layout UI controls to delay hiding the
	 * system UI. This is to prevent the jarring behavior of controls going away
	 * while interacting with activity UI.
	 */
	View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			if (AUTO_HIDE) {
				delayedHide(AUTO_HIDE_DELAY_MILLIS);
			}
			return false;
		}
	};

	Handler mHideHandler = new Handler();
	Runnable mHideRunnable = new Runnable() {
		@Override
		public void run() {
			mSystemUiHider.hide();
		}
	};

	/**
	 * Schedules a call to hide() in [delay] milliseconds, canceling any
	 * previously scheduled calls.
	 */
	private void delayedHide(int delayMillis) {
		mHideHandler.removeCallbacks(mHideRunnable);
		mHideHandler.postDelayed(mHideRunnable, delayMillis);
	}
	
	/*
	 * 
	 * This area is createed for those foundational methods
	 */
	public void post_mission(View view){
		progress = ProgressDialog.show(MissionSignFullscreenActivity.this, "update mission", "waiting..",true,false);
		
		
		/* 
		 * Do net work
		 * 完成任务的提交
		 */
		final MissionDataBase missDBase  = new MissionDataBase(context_this_activity);
		final ContentValues tempValues = new ContentValues();
		
		final String mission_up_email = new Personal_Info_database(context_this_activity).searchEmail(uid);
		final String now_time = String.valueOf(TimeHelper.getNowTimeLong());
		final String mission_name = mission_create_name.getText().toString();
		final String mission_access_num =  access_num.getText().toString();
		final String mission_describe = mission_create_describe.getText().toString();
		final String mission_up_name = new Personal_Info_database(context_this_activity).searchName(uid);
		if (GEO_INFO== null && AddrStr == null){
			Toast.makeText(
					context_this_activity,
					"no place to play!", 
					Toast.LENGTH_SHORT
					).show();
			
			progress.dismiss();
			Intent intent = new Intent(context_this_activity,
					MapMainActivity.class);
			MissionSignFullscreenActivity.this.startActivityForResult(intent
					, MissionSignFullscreenActivity.Choose_place);

			return ;
		}
		if (continue_time.getText().toString().equals("任务时间") ){
			Toast.makeText(
					context_this_activity,
					"no time describtion !!", 
					Toast.LENGTH_SHORT
					).show();
			progress.dismiss();
			return ;
		}
		final String mission_continue = continue_time.getText().toString();
		Log.d("CACHE","continue time: "+mission_continue);
		final int[] Ponter_info = GEO_INFO;
		final int[] User_info = User_geo_info;
		final String User_info_str =  User_addrStr;
		final String mission_place_name = mission_place.getText().toString();
		if (mission_place_name.length() <= 1){
			Intent intent = new Intent(context_this_activity,
					MapMainActivity.class);
			MissionSignFullscreenActivity.this.startActivityForResult(intent
					, MissionSignFullscreenActivity.Choose_place);

		}
		//String temp_tag = "";
		//for (String item : Tag_list){
		//	temp_tag += item;
		//}
		//final String[] mission_tag = [];
			//	Tag_list.;
		
		
		
		//set image's attributes.
		mission_create_picture.setDrawingCacheEnabled(true);
		
		Bitmap bitmap = Bitmap.createBitmap(mission_create_picture.getDrawingCache());
		final byte[] mission_image = BitmapHelper.getByteByBitmap(bitmap);
		mission_create_picture.setDrawingCacheEnabled(false);
		String png_base64_string = BitmapHelper.TurnToBase64(mission_image);
		/*
		 * add arguments to json
		 */
		JSONObject json = new JSONObject();
		JSONArray tags_jsonArray = new JSONArray();
		String tagString = "";
		for (String item : Tag_list){
			tags_jsonArray.put(item);
			tagString += item + " ";
		}
		final String  mission_tag_string = tagString;
		JSONObject picture_json = new JSONObject();
		try {
			json.put("mission_name", mission_name);
			json.put("mission_tag", tags_jsonArray);
			json.put("mission_description", mission_describe);
			json.put("mission_begin_time",now_time);
			json.put("mission_continue",mission_continue );
			Personal_Info_database DB = new Personal_Info_database(context_this_activity);
			Log.d("I_GET","this activity uid :" +uid);
			final String up_email = DB.searchEmail(uid);
			json.put("mission_up_email", up_email);
			json.put("mission_place_latitude", Ponter_info[0]);
			json.put("mission_place_longitude", Ponter_info[1]);
			json.put("mission_place_name", AddrStr);
			json.put("mission_accept_num", mission_access_num);
			json.put("mission_up_name", mission_up_name);
			//
			json.put("user_info_geo_latitude", User_info[0]);
			json.put("user_info_geo_longitude", User_info[1]);
			json.put("user_info_str", User_info_str);
			//
			picture_json.put("mission_name", mission_name);
			picture_json.put("mission_up_email", up_email);
			picture_json.put("mission_picture", png_base64_string);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		/**
		 * update string information .
		 */
		new UpdateMission(this).Update(this.UpdateUrl,json,ARGUMENTS.POST_ARGUMETN_CREATE_ITEM,new AfterSuccessListener(){

			@Override
			public void AfterSuccess(String resultCode) {
				// TODO Auto-generated method stub
				try {
					JSONObject jsonResult = new JSONObject(resultCode);
					String mission_uid  = jsonResult.getString("response");
					tempValues.put(MissionDataBase. MISS_OBJ_ID, mission_uid);
					tempValues.put(MissionDataBase.MISSION_NAME, mission_name);
					tempValues.put(MissionDataBase.MISSION_TAG, mission_tag_string);
					tempValues.put(MissionDataBase.MISSION_UP_EMAIL, mission_up_email);
					tempValues.put(MissionDataBase.UP_NAME, mission_up_name);
					tempValues.put(MissionDataBase.ATTENDEE, "");
					tempValues.put(MissionDataBase.TIME_S,now_time );
					tempValues.put(MissionDataBase.TIME_C, mission_continue);
					tempValues.put(MissionDataBase.LATITUDE,String.valueOf( Ponter_info[0]));
					tempValues.put(MissionDataBase.LONGITUDE, String.valueOf(Ponter_info[1]));
					tempValues.put(MissionDataBase.PLACE_NAME, AddrStr);
					
					//Toast.makeText(context_this_activity, mission_uid, Toast.LENGTH_SHORT).show();
					//insert my info into DB.
					Log.d("CACHE","DB key email :"+mission_up_email);
					String ifNullString = missDBase.search(now_time, MissionDataBase.TIME_S, MissionDataBase.MISS_OBJ_ID);
					if(ifNullString == null ){
						missDBase.insertMission(tempValues);
					}else {
						Log.d("CACHE","if null :"+ifNullString);
				
					}
					Toast.makeText(context_this_activity,  "Mission ID :"+mission_uid+"\n"+User_info.toString()+"\n"+Ponter_info.toString() , Toast.LENGTH_SHORT).show();
				
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		});
		/**
		 * update image info.
		 */
		new UpdateMission(this).Update(ARGUMENTS.UP_MISSION_IMAGE_IP,picture_json,ARGUMENTS.UP_MISSION_IMAGE,new AfterSuccessListener(){

			@Override
			public void AfterSuccess(String resultCode) {
				// TODO Auto-generated method stub
				try {
					JSONObject jsonResult = new JSONObject(resultCode);
					String res  = jsonResult.getString("response");
					//String [] list= BitmapHelper.SaveImage(mission_image);
					//String list_p = null;
					//for (String i : list){
					//	list_p += i+"\n";
					//}
					Toast.makeText(context_this_activity,"picture : update successful :"+res, Toast.LENGTH_SHORT).show();
					
					progress.dismiss();
					ifCreateSuccess = true;
					//new AlertDialog.Builder(MissionSignFullscreenActivity.this)
						//.setTitle("picture")
						//.setMessage(list_p+ARGUMENTS.getPicturePath()).show();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		});
				
				
		if (ifCreateSuccess){
			this.finish();
		}
				
}
				
				
		
		
	
	public void Initialization(){
		my_picture = (ImageView) findViewById(R.id.my_picture);
		access_num = (TextView)findViewById(R.id.mission_access_num);
		mission_create_picture = (ImageView) findViewById(R.id.mission_create_picture);
		mission_create_name  = (EditText)findViewById(R.id.mission_create_name);
		mission_create_describe = (TextView)findViewById(R.id.mission_describe_information);
		continue_time = (TextView)findViewById(R.id.continue_time);
		mission_place = (Button)findViewById(R.id.mission_place);
		/*
		 *change  
		 */
		mission_create_picture.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//String imageName = String.valueOf(System.currentTimeMillis());
				
				//implement take a photo in a huge scale
				
				//BitmapHelper.takePhoto(imageName, MissionSignFullscreenActivity.this);
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				MissionSignFullscreenActivity.this.startActivityForResult(intent, TakePhoto_TAG);
			}
			
		});
		
		//Internet task
		LocationServer = new BaiduLocationServer(context_this_activity);
		LocationServer.RunLocationServer(new BDLocationListener(){

			@Override
			public void onReceiveLocation(BDLocation result) {
				// TODO Auto-generated method stub
				if (LocationServer.qLocationClient == null ){
					return ;
				}
				int latitude =(int) (result.getLatitude() *1E6);
				int longitude = (int)(result.getLongitude()*1E6);
				int[] temp = {latitude,longitude};
				User_geo_info = temp; 
				String  addrStr = null;
				if (result.getLocType() == BDLocation.TypeNetWorkLocation){
					addrStr = result.getAddrStr();
					User_addrStr = addrStr;
				}
				//just for test 
				Log.d(tag,"location run...");
				Toast.makeText(context_this_activity, addrStr, Toast.LENGTH_SHORT).show();
//				turn+=1;
//				if (turn >5){
//					LocationServer.qLocationClient.stop();
//				}
				BaiduLocationServer.turn += 1;
				LocationServer.OFF(3);
			}

			@Override
			public void onReceivePoi(BDLocation arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
	}
	
	@Override 
	public void onActivityResult(int requestCode,int resultCode ,Intent data){
		switch (requestCode){
		case DetailInfoFactory_TAG:
			//deal with some complex operation
			if (resultCode == RESULT_OK && data != null){
				String info = data.getStringExtra("detail_info");
				
				String numString = data.getStringExtra(DetailInfoFactoryActivity.ACCESS_NUM);
				mission_create_describe.setText(info);
				access_num.setText(numString);
				Log.d(tag, "mission access : "+numString);
			}
			break;
		case AddTag_TAG:
			//deal with some complex operation
			if (resultCode == RESULT_OK && data != null){
				LinearLayout layout = (LinearLayout) findViewById(R.id.mission_create_tag);
				
				//initial views group 
				layout.removeAllViews();
				
				String[] Tags = data.getStringArrayExtra("tags");
				for (String tag : Tags){
					Tag_list.add(tag);
					LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT
									, LinearLayout.LayoutParams.WRAP_CONTENT);
					lp.setMargins(6, 0, 0, 0);
					TextView tv = new TextView(this);
					tv.setText(tag);
					tv.setLayoutParams(lp);
					tv.setPadding(6, 0, 0, 0);
					tv.setBackgroundResource(R.drawable.shape_deepskyblue_corner);
					layout.addView(tv);
				}
				String time = data.getStringExtra("time");
				LinearLayout layout_time = (LinearLayout) findViewById(R.id.mission_dead_time);
				TextView tv_time = (TextView) layout_time.getChildAt(0);
				tv_time.setText(time);
				//Toast.makeText(context_this_activity, time, Toast.LENGTH_SHORT).show();
				
			}
			break;
			
		case TakePhoto_TAG:
			//deal with some complex operation
			if (resultCode == RESULT_OK && data != null){
				Bundle image = data.getExtras();
				Bitmap data_image = (Bitmap)image.get("data");
				mission_create_picture.setImageBitmap(data_image);
			}
			break;
		case Choose_place :
			if (resultCode == RESULT_OK && data != null){
				int[] temp = {
						data.getIntegerArrayListExtra("place").get(0),
						data.getIntegerArrayListExtra("place").get(1)
					};
				GEO_INFO  = temp;
				AddrStr = data.getStringExtra("placeStr");
				Toast.makeText(context_this_activity, "Mission place:\t"+AddrStr, Toast.LENGTH_SHORT).show();
				mission_place.setText(AddrStr);
			}
			break;
			
		}
	}
	
	/*
	 * Methods area
	 */
	public void DetailInfoFactory(View view){
		Intent intent = new Intent (context_this_activity
				,DetailInfoFactoryActivity.class);
		MissionSignFullscreenActivity.this.startActivityForResult(intent
					, MissionSignFullscreenActivity.DetailInfoFactory_TAG);
		
	}
	
	public void AddTag(View view){
		Intent intent = new Intent (context_this_activity
				,AddTagTimeActivity.class);
		MissionSignFullscreenActivity.this.startActivityForResult(intent
					, MissionSignFullscreenActivity.AddTag_TAG);
		
	}
	
	public void Destination(View v){
		
//		Intent intent = new Intent(context_this_activity,
//				MapMainActivity.class);
//		MissionSignFullscreenActivity.this.startActivityForResult(intent
//				, MissionSignFullscreenActivity.Choose_place);
	}
	
	
}
